import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import type { ChatSession, ChatSessionParams } from '@/types/chat';
import { Prisma } from '@prisma/client';
import { Page } from '@/types/page';

// POST /api/client/chat/sessions/page - 获取聊天会话分页列表
async function handlePost(request: NextRequest): Promise<Page<ChatSession>> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前用户ID
  const userId = authResult.user?.id;
  if (!userId) {
    throw new Error('用户信息不存在');
  }

  // 3. 解析查询参数
  const body: ChatSessionParams = await request.json();
  const page = Math.max(1, body.page || 1);
  const pageSize = Math.max(1, body.pageSize || 10);
  const search = body.search || '';

  // 4. 构建查询条件
  const where: Prisma.ChatSessionWhereInput = {
    userId: userId,
  };

  // 全局模糊搜索
  if (search) {
    where.OR = [
      { title: { contains: search, } },
      { messages: { some: { content: { contains: search, } } } }
    ];
  }

  // 5. 查询总数和数据
  const total = await prisma.chatSession.count({ where });
  const sessions = await prisma.chatSession.findMany({
    where,
    include: {
      _count: {
        select: {
          messages: true
        }
      }
    },
    orderBy: [
      { updatedAt: 'desc' }
    ],
    skip: (page - 1) * pageSize,
    take: pageSize
  });

  // 6. 数据转换
  const records = sessions.map(session => ({
    id: session.id,
    chatId: session.chatId,
    title: session.title || '新对话',
    userId: session.userId,
    createdAt: session.createdAt.toISOString(),
    updatedAt: session.updatedAt.toISOString(),
    messageCount: session._count.messages,
  }));

  return {
    records,
    total,
    page,
    pageSize
  };
}

export const POST = withMiddleware(handlePost);
